package me.numark.view;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.squareup.picasso.Picasso;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import me.numark.ArticleActivity;
import me.numark.CommentActivity;
import me.numark.NumarkApplication;
import me.numark.ProfileActivity;
import me.numark.R;
import me.numark.ShareActivity;
import me.numark.model.Feed;
import me.numark.model.ForwardResponse;
import me.numark.net.GsonRequest;
import me.numark.net.NetworkConstants;
import me.numark.net.NetworkHelper;
import me.numark.providers.Numa;
import me.numark.utils.Constants;
import me.numark.utils.ImageUtils;
import me.numark.utils.LogUtils;
import me.numark.utils.Settings;
import me.numark.utils.Utils;

/**
 * Created by tian on 14/12/2:上午8:40.
 */
public class FeedViewHolder implements View.OnClickListener {

    @InjectView(R.id.forward_persons)
    public TextView forwardPersons;

    @InjectView(R.id.person_divider)
    public View personDivider;

    @InjectView(R.id.avatar)
    public CircleImageView avatar;

    @InjectView(R.id.name)
    public TextView name;

    @InjectView(R.id.retweet_time)
    public TextView time;

    @InjectView(R.id.retweet_comments)
    public TextView retweetComments;

    @InjectView(R.id.news_icon)
    public ImageView icon;

    @InjectView(R.id.news_title)
    public TextView title;

    @InjectView(R.id.news_time)
    public TextView newsTime;

    @InjectView(R.id.news_source)
    public TextView source;

    @InjectView(R.id.like)
    public TextView like;

    @InjectView(R.id.comment)
    public TextView comment;

    @InjectView(R.id.retweet)
    public TextView retweet;

    @InjectView(R.id.share)
    public ImageView share;

    @InjectView(R.id.news)
    public View news;

    @InjectView(R.id.news_item_divider)
    public View news_item_divider;

    @InjectView(R.id.news_container)
    public View news_container;

    private Context mContext;

    private Feed mFeed;

    public FeedViewHolder(View view, Context context) {
        ButterKnife.inject(this, view);
        forwardPersons.setMovementMethod(LinkMovementMethod.getInstance());
        mContext = context;
        avatar.setOnClickListener(this);
        name.setOnClickListener(this);
        retweetComments.setOnClickListener(this);
        retweet.setOnClickListener(this);
        like.setOnClickListener(this);
        comment.setOnClickListener(this);
        share.setOnClickListener(this);
        news.setOnClickListener(this);
    }

    public void bindFeedView(Feed feed, Date today, Date yesterday, Date year,
            boolean shouldShowNewsView) {
        mFeed = feed;
        LogUtils.d("bindFeedView, data is " + feed.toString());
        if (!TextUtils.isEmpty(feed.user.pic)) {
            Picasso.with(mContext).load(feed.user.pic).into(avatar);
        }
        if (feed.forward_person != null && feed.forward_person.length > 0) {
            forwardPersons.setText(Feed.getForwardPersonText(feed.forward_person));
            forwardPersons.setVisibility(View.VISIBLE);
            personDivider.setVisibility(View.VISIBLE);
        } else {
            forwardPersons.setVisibility(View.GONE);
            personDivider.setVisibility(View.GONE);
        }
        news
                .setBackgroundColor(mContext.getResources().getColor(R.color.feed_news_item_bg));
        name.setText(feed.user.nick);
        time.setText(Utils.getTimeShowText(feed.getDate(), yesterday, today, year));
        retweetComments.setText(feed.description);
        if (!TextUtils.isEmpty(feed.news.face_img)) {
            Picasso.with(mContext).load(feed.news.face_img).into(icon);
        }
        title.setText(feed.news.title);
        newsTime.setVisibility(View.INVISIBLE);
        source.setText(feed.news.from_str);
        like.setText(Integer.toString(feed.like));
        like.setCompoundDrawablesWithIntrinsicBounds(
                feed.is_like ? R.drawable.liked : R.drawable.like_button, 0, 0, 0);
        comment.setText(Integer.toString(feed.comments));
        retweet.setText(Integer.toString(feed.forward));
        news_item_divider.setVisibility(View.GONE);
        if (!shouldShowNewsView) {
            news_container.setVisibility(View.GONE);
        } else {
            news_container.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.avatar:
            case R.id.name:
                intent = new Intent(mContext, ProfileActivity.class);
                intent.putExtra(ProfileActivity.EXTRA_UID, String.valueOf(mFeed.user.uid));
                mContext.startActivity(intent);
                break;
            case R.id.retweet_comments:
                intent = new Intent(mContext, CommentActivity.class);
                intent.putExtra(Constants.FEED_EXTRA, mFeed.toString());
                mContext.startActivity(intent);
                break;
            case R.id.news:
                intent = new Intent(mContext, ArticleActivity.class);
                intent.putExtra(Constants.NEWS_EXTRA, mFeed.news.toString());
                intent.putExtra(Constants.SHARE_COUNT, mFeed.news.share_count);
                mContext.startActivity(intent);
                break;
            case R.id.like: {
                String url = String
                        .format(NetworkConstants.LIKE_URL, Settings.getUid(), mFeed.id);
                GsonRequest<ForwardResponse> request = new GsonRequest<ForwardResponse>(url,
                        Request.Method.GET, ForwardResponse.class, true, null,
                        new Response.Listener<ForwardResponse>() {
                            @Override
                            public void onResponse(ForwardResponse response) {
                                if (response.ret) {
                                    mFeed = response.data;
                                    ContentValues cv = Feed.feedToContentValues(mFeed);
                                    NumarkApplication.getInstance()
                                            .getContentResolver()
                                            .update(Numa.FeedColumns.CONTENT_URI, cv,
                                                    Numa.FeedColumns.FEED_ID + "=?",
                                                    new String[]{Integer.toString(mFeed.id)});
                                } else {
                                    Toast.makeText(mContext, response.msg,
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(mContext, R.string.generic_network_error,
                                Toast.LENGTH_SHORT).show();
                    }
                });
                NetworkHelper.getInstance().addToRequestQueue(request);
                NetworkHelper.getInstance().getRequestQueue().start();
            }
            break;
            case R.id.retweet: {
                if (mFeed.is_mine) {
                    return;
                }
                String url = String
                        .format(NetworkConstants.FORWARD_URL, Settings.getUid());
                Map<String, String> params = new HashMap<String, String>();
                params.put("nsid", Integer.toString(mFeed.id));
                GsonRequest<ForwardResponse> request = new GsonRequest<ForwardResponse>(url,
                        Request.Method.POST, ForwardResponse.class, true, params,
                        new Response.Listener<ForwardResponse>() {
                            @Override
                            public void onResponse(ForwardResponse response) {
                                if (response.ret) {
                                    mFeed = response.data;
                                    response.data.news = mFeed.news;
                                    ContentValues cv = Feed.feedToContentValues(response.data);
                                    NumarkApplication.getInstance().getContentResolver().update(
                                            Numa.FeedColumns.CONTENT_URI, cv,
                                            Numa.FeedColumns.FEED_ID + "=?",
                                            new String[]{Integer.toString(mFeed.id)});
                                } else {
                                    Toast.makeText(mContext, response.msg,
                                            Toast.LENGTH_SHORT).show();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(mContext, R.string.generic_network_error,
                                Toast.LENGTH_SHORT).show();
                    }
                });
                NetworkHelper.getInstance().addToRequestQueue(request);
                NetworkHelper.getInstance().getRequestQueue().start();
            }
            break;
            case R.id.comment:
                intent = new Intent(mContext, CommentActivity.class);
                intent.putExtra(Constants.FEED_EXTRA, mFeed.toString());
                mContext.startActivity(intent);
                break;
            case R.id.share:
                if (mFeed.is_mine) {
                    return;
                }
                icon.buildDrawingCache();
                File file = ImageUtils.saveImage(icon.getDrawingCache());
                intent = new Intent(mContext, ShareActivity.class);
                intent.putExtra(Constants.FEED_EXTRA, mFeed.toString());
                intent.putExtra(Constants.PICTURE_EXTRA, file.getAbsolutePath());
                mContext.startActivity(intent);
                break;
            default:
                break;
        }
    }
}
